﻿using System.Collections.Generic;
using System.Linq;
using com.cruxomatic.DTOs;
using com.cruxomatic.BusinessObjects;
using com.cruxomatic.BusinessObjects.DatabaseQueries;
using com.cruxomatic.exceptions;

namespace com.cruxomatic.BusinessFacades
{
    public class SubLocationFacade
    {
        public List<SubLocationInformation> GetSubLocations(int LocationID)
        {
            Queries locationsQuery = new Queries();
            IEnumerable<SubLocationInformation> subLocations =
                from subLocationList in locationsQuery.GetSubLocations(LocationID)
                select ClassConverter.CopySubLocationToSubLocationInfomration(subLocationList);
            return subLocations.ToList();
        }

        public SubLocationInformation GetSubLocation(int SubLocationID)
        {
            if (SubLocationID == 0) return new SubLocationInformation();
            Queries locationQuery = new Queries();
            SubLocation subLocation = locationQuery.GetSubLocation(SubLocationID);
            return ClassConverter.CopySubLocationToSubLocationInfomration(subLocation);
        }

        public void SaveSubLocation(SubLocationInformation SubLocation)
        {
            CheckValidity(SubLocation);
            Queries subLocationQuery = new Queries();
            SubLocation dbSubLocation = new SubLocation();
            if (SubLocation.SubLocationID != 0)
                dbSubLocation = subLocationQuery.GetSubLocation(SubLocation.SubLocationID);
            dbSubLocation = ClassConverter.CopySubLocationInformationToSubLocation(SubLocation, dbSubLocation);

            if (SubLocation.SubLocationID != 0)
                subLocationQuery.SubmitChanges();
            else
                subLocationQuery.InserSubLocation(dbSubLocation);

        }

        private void CheckValidity(SubLocationInformation subLocation)
        {
            if (DoesSubLocationExist(subLocation.ParentLocationID, subLocation))
                throw CruxExceptionManager.CreateNewDatabaseException("904");
        }

        public bool DoesSubLocationExist(int locationID, SubLocationInformation subLocation)
        {
            Queries query = new Queries();
            SubLocation dbSubLocation = query.GetSubLocation(locationID, subLocation.SubLocationName);
            if (dbSubLocation != null && subLocation.SubLocationID != dbSubLocation.SubLocationID)
                return true;
            return false;
        }

        public void DeleteSubLocation(int SubLocationID)
        {
            Queries subLocationQuery = new Queries();
            SubLocation subLocation = subLocationQuery.GetSubLocation(SubLocationID);
            subLocationQuery.DeleteSubLocation(subLocation);
        }
    }
}
